package QuickList;

import ZipList.ZipListEntry;

public class QuickList {
    QuickListNode head; // 头节点
    QuickListNode tail; // 尾节点
    private int length; // 链表长度
    private final int fill; // 链表填充因子（每个ZipList中最大的ZipListEntry数）

    public QuickList(int maxZipListEntrySize) {
        this.head = null;
        this.tail = null;
        this.length = 0;
        this.fill = maxZipListEntrySize;
    }

    // 插入
    public void insert(byte[] data) {
        // 如果链表为空，或者尾节点的ZipList已满，则创建新节点
        if (tail == null || tail.getZipList().getSize() >= fill) {
            QuickListNode newNode = new QuickListNode(fill);
            if (tail == null) {
                head = tail = newNode;
            } else {
                tail.next = newNode;
                newNode.prev = tail;
                tail = newNode;
            }
        }

        // 将数据插入到尾节点的ZipList中
        tail.getZipList().insert(data);
        length++;
    }

    // 获取QuickList中全部元素
    public ZipListEntry[] getAllData() {
        ZipListEntry[] allData = new ZipListEntry[length];
        QuickListNode wordNode = head;
        int allDataIndex = 0;
        while (wordNode != null) {
            ZipListEntry[] zipListEntries = wordNode.getZipList().getAllData();
            for (ZipListEntry zipListEntry : zipListEntries) {
                allData[allDataIndex++] = zipListEntry;
            }
            wordNode = wordNode.next;
        }
        return allData;
    }

    // 逆向获取QuickList中全部元素
    public ZipListEntry[] getAllDataReverse() {
        ZipListEntry[] allData = new ZipListEntry[length];
        QuickListNode wordNode = tail;
        int allDataIndex = 0;
        while (wordNode != null) {
            ZipListEntry[] zipListEntries = wordNode.getZipList().getAllData();
            for (int i = zipListEntries.length - 1; i >= 0; i--) {
                allData[allDataIndex++] = zipListEntries[i];
            }
            wordNode = wordNode.prev;
        }
        return allData;
    }
}
